#include "delay.h"
#include "main.h"

static void DelayTim2()
{
    TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
    TIM_TimeBaseStructure.TIM_Period = 1;
    TIM_TimeBaseStructure.TIM_Prescaler = ((SystemCoreClock / 2 / 1000000) - 1);
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Down;
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
}

static void DelayTim3()
{
    TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
    TIM_TimeBaseStructure.TIM_Period = 1;
    TIM_TimeBaseStructure.TIM_Prescaler = ((SystemCoreClock / 2 / 1000) - 1);
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Down;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
}

void Delay_Configuration(void)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
    DelayTim2();
    DelayTim3();
}

void delay_n_us(u16 delay)
{
    TIM_Cmd(TIM2, ENABLE);
    TIM_SetCounter(TIM2, delay);

    while(delay > 1)
    {
        delay = TIM_GetCounter(TIM2);
    }
    TIM_Cmd(TIM2, DISABLE);
}

void delay_n_ms(u16 delay)
{
    TIM_Cmd(TIM3, ENABLE);
    TIM_SetCounter(TIM3, delay);

    while(delay > 1)
    {
        delay = TIM_GetCounter(TIM3);
    }
    TIM_Cmd(TIM3, DISABLE);
}

void delay_n_s(u8 delay)
{
    u32 delay_s = LocalTime;

    do
    {
        ;
    }
    while(LocalTime < delay_s + delay * 1000);
}
